import { registerLocaleData } from '@angular/common';
import { AppComponentBase } from '@shared/common/app-component-base';
import { MapCircleModalComponent } from './../map-circle-modal/map-circle-modal.component';
import { SiteDTO } from './../../../shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, Injector } from '@angular/core';
import { ServiceProxy, UserInfoDTO, WarehouseDTO, DictionaryDTO } from '@shared/service-proxy/service-proxies';
import {
  FormBuilder,
  FormGroup,
  Validators
} from '@angular/forms';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { finalize } from 'rxjs/operators';
import { SetWarehouseReasonModalComponent } from './set-warehouse-reason-modal/set-warehouse-reason-modal.component';
import { FileUploader } from 'ng2-file-upload';
import { AppConsts } from '@shared/AppConsts';

@Component({
  selector: 'app-warehouse-company',
  templateUrl: './warehouse-company.component.html',
  styleUrls: ['./warehouse-company.component.less']
})
export class WarehouseCompanyComponent extends AppComponentBase implements OnInit {

  @ViewChild('mapCircleModal') mapCircleModal: MapCircleModalComponent;
  @ViewChild('setWarhouseReasonkModal') setWarhouseReasonkModal: SetWarehouseReasonModalComponent;
  @ViewChild('fileSelect') uploadImg: any;
  tableHelper: NzTableHelper;
  uploader: FileUploader;
  loading = true;
  isOkLoading = false;
  keyword: string;
  title: string;

  warnHouse: WarehouseDTO = new WarehouseDTO();
  sites: SiteDTO[] = [];
  users: UserInfoDTO[] = [];

  isVisible = false;
  validateForm: FormGroup;


  constructor(injector: Injector, private fb: FormBuilder, private _service: ServiceProxy) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }


  ngOnInit() {
    this.getUsers();
    this.getSites();
    this.load();
    this.validateForm = this.fb.group({
      houseName: [null, [Validators.required, Validators.maxLength(10)]],
      // address: [null, [Validators.required]],
      siteId: [null, [Validators.required]],
      managerName: [null, [Validators.required]],
      managerPhone: [null, [Validators.required]],
      housePhone: [null, [Validators.required]],
      lat: [null, [Validators.required]],
      lng: [null, [Validators.required]],
      // radius: [null, [Validators.required]]
    });
    this.initUploaders();
  }

  getUsers() {
    this._service.getAllUserInfoListUsingGET().subscribe(result => {
      this.users = result.result.fieldList;
    })
  }

  getSites() {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })
  }


  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.getPageWarehouseDTOsUsingGET(this.tableHelper.pageIndex, this.tableHelper.pageSize, this.keyword).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result.fieldList;
      this.tableHelper.totalCount = result.result.totalRow;
    });
  }

  reset() {
    this.keyword = undefined;
    this.load();
  }

  showModal(houseId?: string): void {
    this.warnHouse = new WarehouseDTO();
    if (houseId) {
      this._service.getWarehouseUsingGET(houseId).subscribe(result => {
        this.warnHouse = result.result;
      });
      this.title = this.l("edit");
    }
    else {
      this.validateForm.reset();
      this.title = this.l("create");
    }
    this.isVisible = true;
  }


  checkLong(lng: number): boolean {
    if(!lng){
      return false;
    }
    var lngStr = lng.toString();
    
    var longrg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;

    if (!longrg.test(lngStr)) {
      this.message.error('经度整数部分为0-180,小数部分为0到6位!');
      return false
    }
    return true;
  }
  checkLat(lat: number): boolean {
    if(!lat){
      return false
    }
    var latStr = lat.toString();
    var latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
    if (!latreg.test(latStr)) {
      this.message.error(this.l('verify_failed_please_check_the_form_item'));//'纬度整数部分为0-90,小数部分为0到6位!');
      return false;
    }
    return true;
  }

  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (!this.checkLong(this.warnHouse.lng) || !this.checkLat(this.warnHouse.lat)) {
      this.isOkLoading = false;
      return;
    }
    if (this.validateForm.valid) { // 验证通过
      if (this.warnHouse.id) {
        this._service.updateWarehouseUsingPUT(this.warnHouse, this.warnHouse.id).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisible = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        }
        )
      }
      else {
        this._service.createWarehouseUsingPOST(this.warnHouse).subscribe(result => {
          this.isOkLoading = false;
          if (result.success) {
            this.message.success(this.l("save_success"));
            this.load();
            this.isVisible = false;
          }
          else {
            this.message.info(this.l(result.error.message));
          }
        }, error => {
          this.isOkLoading = false;
          this.message.error(error.message);
        })
      }
    } else { // 验证未通过
      this.isOkLoading = false;
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  handleUsing(company: WarehouseDTO) {
    this.setWarhouseReasonkModal.show(company.id, company.enableFlag);
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  showMap(data: any) {
    this.mapCircleModal.show(data.lng, data.lat, data.radius);
  }

  initUploaders(): void {
    this.uploader = new FileUploader({
      url: AppConsts.serverBaseUrl + '/api/siiat/v1/warehouses/batchImport',
      method: 'POST',
      authToken: 'Bearer ' + abp.auth.getToken(),
      removeAfterUpload: true,
      autoUpload: true
    });
    this.uploader.onAfterAddingFile = (file) => {
      file.withCredentials = false;
    };

    this.uploader.onSuccessItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      if (ajaxResponse.success) {
        this.message.success(this.l('upload_success'));
      } else {
        this.message.error(this.l(ajaxResponse.error.message));
      }

      this.uploader.destroy();
      this.initUploaders();
      this.imgCropper();
      this.load();
    };
    this.uploader.onErrorItem = (item, response, status) => {
      const ajaxResponse = JSON.parse(response);
      this.message.error(this.l(ajaxResponse.error.message));
      this.imgCropper();
    };
  }

  imgCropper() {
    // 一系列操作
    // 最后把input的value置空
    this.uploadImg.nativeElement.value = '';
  }


}
